const Role = require('../../models/system/role');

const addRole = async (req, res, next) => {
  try {
    const { roleName } = req.body;
    const role = await Role.findOne({roleName});
    if(role) {
      if(roleName == role.roleName){
        return res.send({
          code: 1001,
          msg: '角色已存在'
        })
      }
    }
    await Role.create(req.body);
    res.send({
      code: 200,
      msg: '添加成功'
    })
  } catch (error) {
    next(error)
  }
}

const editRole = async (req, res, next) => {
  try{
    const { id, roleName, roleType, status, remark, order } = req.body;
    const role = await Role.findOne({_id: id});
    if(roleName == role.roleName & roleType == role.roleType & status == role.status & remark == role.remark & order == role.order){
      return res.send({
        code: 1001,
        msg: '角色信息未修改'
      })
    }
    await Role.findOneAndUpdate({_id: id}, req.body)
    res.send({
      code: 200,
      msg: '修改成功'
    })
  } catch (error){
    next(error)
  }
}

const queryRoleList = async (req, res, next) => {
  try {
    const { page, pageSize, roleName, roleType, status } = req.query;
    let arr = []
    if(roleName || roleType || status){
      arr = await Role.find({$or:[{roleName: roleName},{roleType: roleType},{status: status}]});
    }else{
      arr = await Role.find().skip(pageSize*(page-1)).limit(pageSize).sort({_id: -1});
    }
    arr.forEach(element => {
      element.id = element._id
    });
    res.send({
      code: res.statusCode,
      msg: '查询成功',
      data: {
        list: arr
      }
    })
  } catch (error) {
    next(error)
  }
}

const roleDetail = async (req, res, next) => {
  try {
    const { id } = req.query;
    const role = await Role.findById({_id: id});
    if(!role){
      return res.send({
        code: 1001,
        msg: '参数错误',
        data: null
      })
    }
    res.send({
      code: 200,
      msg: '成功',
    })
  } catch (error) {
    next(error)
  }
}

const deleteRole = async (req, res, next) => {
  try {
    const { id } = req.params
    const role = await Role.deleteOne({_id: id});
    if(!role){
      return res.status(404).send({
        code: 1001,
        msg: '参数错误',
        data: null
      })
    }
    res.send({
      code: 200,
      msg: '删除成功'
    })
  } catch (error) {
    next(error)
  }
}

module.exports = {
  addRole,
  editRole,
  queryRoleList,
  roleDetail,
  deleteRole
}